#include "mainwindow.h"

#include "qnewprojectdialog.h"
#include "fancytabwidget.h"
#include "qupdatechoosedialog.h"
#include "qsyncchoosedialog.h"

#include "../libs/sharedlib/pluginloader.h"
#include "../libs/corelib/qabstractpagewidget.h"
#include "../libs/sharedlib/qabstractpage.h"
#include "../libs/corelib/qsoftcore.h"
#include "../libs/corelib/manhattanstyle.h"
#include "../libs/sharedLib/qprojectcore.h"
#include "../libs/sharedLib/qcommonstruct.h"
#include "../libs/runningLib/qrunningcore.h"


#include <QSettings>
#include <QDesktopWidget>
#include <QFile>
#include <QApplication>
#include <QCloseEvent>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),
    m_fancyTab(new FancyTabWidget(this)),
    m_menuBar(new QMenuBar(this)),
    m_runningWindow(NULL)
{
    qApp->setStyle(new CORELIB::ManhattanStyle(QApplication::style()->objectName()));
    this->setCentralWidget(m_fancyTab);

    connect(m_fancyTab,SIGNAL(currentChanged(int)),this,SLOT(page_changed(int)));

    SHAREDLIB::PluginLoader* l=SHAREDLIB::PluginLoader::getPluginLoader();
    QStringList pages=CORELIB::QSoftCore::getCore()->pages();
    foreach(QString str,pages)
    {
        QAbstractPage* page=l->getTabPagePlugin(str);
        int i;
        for(i=0;i<m_pages.size();i++)
        {
            if(page->getIndex()<m_pages.at(i)->getIndex())
            {
                m_pages.insert(i,page);
                break;
            }
        }
        if(i==m_pages.size())
        {
            m_pages.append(page);
        }
    }
    foreach(QAbstractPage* p,m_pages)
    {
        m_fancyTab->insertTab(m_pages.indexOf(p),p->getWidget(),p->getPageIcon(),p->getPageName());
    }

    CORELIB::QSoftCore *core=CORELIB::QSoftCore::getCore();
    SHAREDLIB::QProjectCore *pc=SHAREDLIB::QProjectCore::getCore();
    QAction *ac;

    ac=core->action("Debug-Run");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),this,SLOT(run()));
    }

    ac=core->action("Debug-Stop");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),this,SLOT(stop()));
        m_fancyTab->setButtonVisible(ac,false);
    }

    ac=core->action("Project-New");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),this,SLOT(newProject()));
    }

    ac=core->action("Project-Close");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),pc,SLOT(closed()));
    }

    ac=core->action("Project-Save");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),pc,SLOT(save()));
    }

    ac=core->action("Project-Open");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),this,SLOT(openProject()));
    }

    ac=core->action("Device-Update");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),this,SLOT(showDevice()));
    }

    ac=core->action("Device-Sync");
    if(ac!=NULL)
    {
        connect(ac,SIGNAL(triggered()),this,SLOT(showSyncChoose()));
    }

    connect(pc,SIGNAL(projectOpen()),this,SLOT(projectOpen()));
    connect(pc,SIGNAL(projectClosed()),this,SLOT(projectClosed()));

    connect(core,SIGNAL(pageAt(QVariant)),this,SLOT(pageAt(QVariant)));

    initMenuBar();
    this->setMenuBar(m_menuBar);

    m_fancyTab->setCurrentIndex(0);
}

MainWindow::~MainWindow()
{
}

void MainWindow::show()
{
    QSettings s(qApp->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    QVariant v=s.value("window/geometry");
    if(v.isValid())
    {
        restoreGeometry(v.toByteArray());
    }
    else
    {
        QDesktopWidget* dw=qApp->desktop();
        setGeometry(dw->width()/10,dw->height()/10,dw->width()*4/5,dw->height()*4/5);

        saveSetting();
    }
    QMainWindow::show();
}


void MainWindow::saveSetting()
{
    QFile f(qApp->applicationDirPath()+"/config.ini");
    if(!f.exists())
    {
        f.open(QIODevice::WriteOnly);
        f.resize(0);
        f.close();
    }

    QSettings s(qApp->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    s.setValue("window/geometry",saveGeometry());
}

void MainWindow::newProject()
{
    QNewProjectDialog dlg(this);
    dlg.exec();
    QString name=dlg.getName();
    QString path=dlg.getPath();
    if(name!="" && path!="")
    {
        SHAREDLIB::QProjectCore::getCore()->create(path,name);
    }
}

void MainWindow::projectOpen()
{
    this->setWindowTitle(SHAREDLIB::QProjectCore::getCore()->getPropertyValue("name").toString()+"--Soft Configure Project");
}

void MainWindow::projectClosed()
{
    this->setWindowTitle(tr("Soft Configure"));
}

void MainWindow::openProject()
{
    QString file=QFileDialog::getOpenFileName(this,tr("Open Project"),QDir::currentPath(),tr("Project File (*.pro)"));
    if(file!=NULL)
    {
        SHAREDLIB::QProjectCore::getCore()->open(file);
    }
}

void MainWindow::initMenuBar()
{
    QMenu *menu=m_menuBar->addMenu(tr("Project"));

    CORELIB::QSoftCore *core=CORELIB::QSoftCore::getCore();
    QAction *ac;
    ac=core->action("Project-New");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    ac=core->action("Project-Close");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    ac=core->action("Project-Save");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    ac=core->action("Project-Open");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    menu=m_menuBar->addMenu(tr("Edit"));
    ac=core->action("Redo");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    ac=core->action("Undo");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    menu=m_menuBar->addMenu(tr("Device"));
    ac=core->action("Device-Update");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }

    ac=core->action("Device-Sync");
    if(ac!=NULL)
    {
        menu->addAction(ac);
    }
}

void MainWindow::run()
{
    if(m_runningWindow!=NULL)
    {
        return;
    }
    QSettings s(qApp->applicationDirPath()+"/config.ini",QSettings::IniFormat,this);
    s.setValue("project/path",SHAREDLIB::QProjectCore::getCore()->getPropertyValue("path").toString());
    m_runningWindow=new RUNNINGLIB::QRunningWindow(SHAREDLIB::QProjectCore::getCore()->getPropertyValue("path").toString());
    connect(m_runningWindow,SIGNAL(runSignal()),this,SLOT(runSignal()));
    connect(m_runningWindow,SIGNAL(stopSignal()),this,SLOT(stopSignal()));
    SHAREDLIB::QProjectCore::getCore()->save();
    m_fancyTab->setStatusButtonCheck(0,true);
    m_runningWindow->run();
}

void MainWindow::runSignal()
{
    CORELIB::QSoftCore *core=CORELIB::QSoftCore::getCore();
    QAction *ac;

    ac=core->action("Debug-Run");
    m_fancyTab->setButtonVisible(ac,false);
    ac=core->action("Debug-Stop");
    m_fancyTab->setButtonVisible(ac,true);

    ac=core->action("Project-New");
    if(ac!=NULL)
    {
        ac->setEnabled(false);
    }

    ac=core->action("Project-Close");
    if(ac!=NULL)
    {
        ac->setEnabled(false);
    }

    ac=core->action("Project-Save");
    if(ac!=NULL)
    {
        ac->setEnabled(false);
    }

    ac=core->action("Project-Open");
    if(ac!=NULL)
    {
        ac->setEnabled(false);
    }
}

void MainWindow::stop()
{
    if(m_runningWindow==NULL)
    {
        return;
    }
    m_runningWindow->stop();
}

void MainWindow::stopSignal()
{
    CORELIB::QSoftCore *core=CORELIB::QSoftCore::getCore();
    QAction *ac;

    ac=core->action("Debug-Stop");
    m_fancyTab->setButtonVisible(ac,false);
    ac=core->action("Debug-Run");
    m_fancyTab->setButtonVisible(ac,true);
    delete m_runningWindow;
    m_runningWindow=NULL;

    ac=core->action("Project-New");
    if(ac!=NULL)
    {
        ac->setEnabled(true);
    }

    ac=core->action("Project-Close");
    if(ac!=NULL)
    {
        ac->setEnabled(true);
    }

    ac=core->action("Project-Save");
    if(ac!=NULL)
    {
        ac->setEnabled(true);
    }

    ac=core->action("Project-Open");
    if(ac!=NULL)
    {
        ac->setEnabled(true);
    }
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    stop();
    saveSetting();

    QMainWindow::closeEvent(e);
}

void MainWindow::showDevice()
{
    QUpdateChooseDialog dlg(this);
    dlg.exec();
}

void MainWindow::showSyncChoose()
{
    QSyncChooseDialog dlg(this);
    dlg.exec();
}

void MainWindow::page_changed(int index)
{
}

bool MainWindow::pageAt(const QVariant &param)
{
    if(!param.isValid())
    {
        return false;
    }

    tagPagePositionInfo info=param.value<tagPagePositionInfo>();
    QString name=info.m_data.value("page_name").toString();

    if(name!="")
    {
        bool ret=false;

        foreach(QAbstractPage* page,m_pages)
        {
            if(page->getPageName()==name)
            {
                if(m_fancyTab->currentIndex()!=m_pages.indexOf(page))
                {
                    ret=true;
                    m_fancyTab->setCurrentIndex(m_pages.indexOf(page));
                }
                bool b=page->pagePosition(param);
                return ret | b;
            }
        }
    }

    return false;
}
